package my.websocket.download;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.internal.StringUtil;
import my.websocket.util.ThreadUtils;

import java.io.IOException;

public class DownloadTaskHandler extends SimpleChannelInboundHandler<HttpObject> {

    private final String fileName;
    private FileFlushTask fileFlushTask;

    public DownloadTaskHandler(String fileName) {
        this.fileName = fileName;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {

        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;
            Integer contentLength = response.headers().getInt(HttpHeaderNames.CONTENT_LENGTH);
            if (contentLength == null || contentLength <= 0) {
                // 关闭连接
                ctx.close();
                return;
            }
            long fileLength = contentLength.longValue();
            String range = response.headers().get(HttpHeaderNames.CONTENT_RANGE);
            long beginIdx = 0;
            if (!StringUtil.isNullOrEmpty(range)) {
                String[] ranges = range.substring(5).split("-");
                if (ranges.length > 0) {
                    beginIdx = Long.parseLong(ranges[0].trim());
                }
            }
            try {
                fileFlushTask = new FileFlushTask(fileName, fileLength, beginIdx);
                ThreadUtils.BLOCK_EVENT_LOOP_GROUP.execute(fileFlushTask);
            } catch (IOException e) {
                e.printStackTrace();
                ctx.close();
                return;
            }
        }

        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            if (fileFlushTask != null) {
                try {
                    ByteBuf buff = content.content();
                    fileFlushTask.write(buff);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (content instanceof LastHttpContent) {
                if (fileFlushTask != null) {
                    try {
                        fileFlushTask.flush();
                        fileFlushTask.cancel();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                System.err.println("END OF CONTENT");
                ctx.close();
            }
        }
    }
}
